package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 设备管理Service业务层处理
 *
 * @author lww
 * @date 2024-11-18
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private Client client;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        //1,查询阿里iot平台的所有产品
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        // 分页条件
        queryProductListRequest.setPageSize(20);
        queryProductListRequest.setCurrentPage(1);
        // 公共实例
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        // 查询公共实例下的所有产品
        QueryProductListResponse queryProductListResponse = null;
        try {
            queryProductListResponse = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            log.error("查询阿里所有iot产品失败!", e);
            throw new ServiceException("查询阿里所有iot产品失败!");
        }

        //查询所有产品后没有成功
        // 将数据存储到redis中
        if (!queryProductListResponse.getBody().success) {
            throw new ServiceException("查询阿里所有iot产品失败!");
        }
        //转化为vo 对象
        List<ProductVo> productVoList = queryProductListResponse.getBody().getData().getList().getProductInfo().stream()
                .map(pro -> BeanUtil.toBean(pro, ProductVo.class)).collect(Collectors.toList());
        String jsonStr = JSONUtil.toJsonStr(productVoList);
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, jsonStr);
    }

    @Override
    public List<ProductVo> selectAllProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {
        //1.设备名称是否重复
        Device deviceInDb = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).one();
        if (ObjectUtil.isNotEmpty(deviceInDb)) {
            throw new ServiceException("设备名称已存在！" + dto.getDeviceName());
        }
        //2.新增iot新增设备，获取iot_id
        addIotDevice(dto);
        //3.查询产品的名称,从redis中查
        getProductName(dto);

        //4.判断位置类型是不是0，随身设备老人，设置位置为-1
        if (ObjectUtil.equal(dto.getLocationType(), 0)) {
            dto.setPhysicalLocationType(-1);
        }
        //保存设备到数据库
        Device device = BeanUtil.toBeanIgnoreError(dto, Device.class);
        //保存不成功的话，就需要删除iot设备
        try {
            save(device);
        } catch (Exception e) {
            deleteIotDevice(dto.getIotId());
        }

    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {

        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new ServiceException("物联网接口-查询设备，调用失败");
        }
        if (!response.getBody().success) {
            throw new ServiceException("物联网接口-查询设备，调用失败");
        }

        //查询数据库补上缺少的字段
        Device deviceInDB = lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()).one();

        // 查询表中的数据
        DeviceVo deviceVo = BeanUtil.toBean(deviceInDB, DeviceVo.class);

        // 合并
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    @Override
    public Object queryThingModelPublished(DeviceDto deviceDto) {
        QueryThingModelPublishedRequest request = new QueryThingModelPublishedRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());
         try {
             QueryThingModelPublishedResponse response = client.queryThingModelPublished(request);
             if (response.getBody().success){

                return response.getBody().getData();
             }
         } catch (Exception e) {
             log.info("查看指定产品的已发布物模型中的功能定义详情失败{}",request.getProductKey(), e);
         }
         throw new ServiceException("查看指定产品的已发布物模型中的功能定义详情失败");
     }

    @Override
    public Object queryDevicePropertyStatus(DeviceDto deviceDto) {
        QueryDevicePropertyStatusRequest request = new QueryDevicePropertyStatusRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setDeviceName(deviceDto.getDeviceName());
        request.setProductKey(deviceDto.getProductKey());

        try {
            QueryDevicePropertyStatusResponse response = client.queryDevicePropertyStatus(request);
            if (response.getBody().success){
                return response.getBody().getData();
            }
        } catch (Exception e) {
            log.info("查询设备运行状态失败{}", deviceDto.getDeviceName(), e);
        }
            throw new ServiceException("查询设备运行状态失败");

    }


    private void deleteIotDevice(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            log.error("新增设备失败，删除iot设备【{}】失败.", iotId, e);
            throw new ServiceException("新增设备失败,删除设备失败！");
        }
    }

    private void getProductName(DeviceDto dto) {

        String json = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        List<ProductVo> productVoList = JSONUtil.toList(json, ProductVo.class);
        ProductVo productVo = productVoList.stream().filter(product -> product.getProductKey().equals(dto.getProductKey()))
                .findFirst().get();
        dto.setProductName(productVo.getProductName());
    }

    /**
     * 注册iot 设备，返回iot的iot_id
     *
     * @param dto
     */
    private void addIotDevice(DeviceDto dto) {
        try {
            RegisterDeviceRequest request = dto.getRegisterDeviceRequest();
            request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

            RegisterDeviceResponse response = client.registerDevice(request);

            //如果成功就设置iot_id
            if (response.getBody().success) {
                dto.setIotId(response.getBody().getData().getIotId());
                return;
            }
        } catch (Exception e) {
            log.error("注册iot设备出错", e);
        }
        throw new ServiceException("注册iot设备出错");
    }



}
